import { createStore } from 'vuex';

export default createStore({
  state: {
    //token
    auth: localStorage.getItem('Authorization')
      ? localStorage.getItem('Authorization')
      : '',
    userInfo: localStorage.getItem('userInfo')
      ? localStorage.getItem('userInfo')
      : {
          userId: 0,
          username: '',
          password: '',
          email: '',
        },
  },
  getters: {
    getUserInfo(state) {
      if (typeof state.userInfo === 'string') {
        return JSON.parse(state.userInfo);
      } else {
        return state.userInfo;
      }
    },
  },
  mutations: {
    //保存token 和 用户信息
    updateAuth(state, data) {
      state.auth = data.auth;
      state.userInfo = data.userInfo;
      if (data.auth.length <= 0) {
        localStorage.removeItem('Authorization');
        localStorage.removeItem('userInfo');
      } else {
        localStorage.setItem('Authorization', data.auth);
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo));
        console.log(localStorage);
      }
    },
  },
  actions: {},
  modules: {},
});
